package com.programming.forum.interceptor;

import com.programming.forum.config.AppConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 22479
 * Date: 2023-11-07
 * Time: 15:38
 */

/**
 * 登录拦截器
 */
//如果要使用application.yml中的配置属性 需要把类加入到spring中
@Component
public class LoginInterceptor implements HandlerInterceptor {

    //配置文件配置好了默认调整目标页面
    @Value("${forum.login.url}")
    private String defaultURL;

    /**
     * 前置处理(预处理)
     * @return true 则继续处理 false 不继续后面流程
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        if(session == null || session.getAttribute(AppConfig.USER_SESSION) == null) {
            //未登录 跳转到登录页面
            //检测URL是否正确
            if(!defaultURL.startsWith("/")) {
                defaultURL = "/" + defaultURL;
            }
            response.sendRedirect(defaultURL);
            return false;
        }
        //登录 放行
        return true;
    }
}
